<?php
class RoleModel extends Model{
    protected $fields=array(
        'name', 'status', 'remark',
        '_pk'=>'name',
        '_autoInc'=>false
    );

    protected $_auto=array(
        array('name','trim','ALL','function')
    );

    protected $_validate=array(
        array('name','require','{%v_role_name_require}'),
    );

    /**
     * 添加角色
     * 成功返回角色信息，失败返回false
     */
    public function addRole(){
        $roleVo=$this->create();
        if(!$roleVo){
            return false;
        }
        $this->startTrans();
        $ret=$this->add($roleVo);
        if($ret){
            $continue=true;
            //获取权限信息
            if(array_key_exists('popedom',$_POST)){
                $node=new NodeModel();
                $nodeList=$node->field('id,pid,level')->where('menu in (0,'.implode(',', $_POST['popedom']).')')->findAll();
                $access=array();
                foreach($nodeList as $n){
                    $access[]=array(
                        'role'=>$roleVo['name'],
                        'nodeId'=>$n['id'],
                        'level'=>$n['level'],
                        'parentNodeId'=>$n['pid']
                    );
                }
                if(count($access)>0){
                    $accessDao=new AccessModel();
                    if(false===$accessDao->addAll($access)){
                        $continue=false;
                    }
                }
                if($continue){
                    $this->commit();
                    return $roleVo;
                }
            }
        }
        $this->rollback();
        return false;
    }

    public function checkRoleNameUsed($roleName){
        $tmp=$this->where("name='{$roleName}'")->find();
        if($tmp) return true;
        return false;
    }

}
